package com.project.frba.bi.dashboard;

import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.RowMapperResultSetExtractor;

import com.project.frba.bi.queueing.AbstractDAO;
import com.project.frba.bifront.client.model.Dashboard;

public class DashboardDAO extends AbstractDAO{
	
	public Integer createDashoard(String query, Long userId, String dashboardName) {
		Object[] params = new Object[]{
				dashboardName, 
				new Long(userId)
		};
		int[] types = new int[]{Types.VARCHAR, Types.BIGINT};
		return jdbcTemplate.update(query, params, types);
	}

	public List<Dashboard> getDashboardsByUser(String userId) {
		List<Dashboard> userDashboards = new ArrayList<Dashboard>();
		Object[] params = new Object[]{new Long(userId)};
		
		String dualQuery = DashboardQueryBuilder.getAllDualDashboardsFromUser();
		RowMapperResultSetExtractor dualExtractor = new RowMapperResultSetExtractor(new DualDashboardRowMapper());
		List<Dashboard> dualDashboards = (List<Dashboard>)jdbcTemplate.query(dualQuery, params, dualExtractor);
		userDashboards.addAll(dualDashboards);
		
		String quadQuery = DashboardQueryBuilder.getAllQuadDashboardsFromUser();
		RowMapperResultSetExtractor quadExtractor = new RowMapperResultSetExtractor(new QuadDashboardRowMapper());
		List<Dashboard> quadDashboards = (List<Dashboard>)jdbcTemplate.query(quadQuery, params, quadExtractor);
		userDashboards.addAll(quadDashboards);
		
		return userDashboards;
	}

	public void removeDashboard(String query, Long dashboardId) {
		Object[] params = new Object[]{dashboardId};
		jdbcTemplate.update(query, params);
	}

	public void updateDashboard(String query, Object[] params) {
		jdbcTemplate.update(query, params);
	}
	
	public Dashboard findDashboardById(Long dashboardId, Integer type){
		Object[] params = new Object[]{dashboardId};
		
		String query = null;
		RowMapper mapper = null;
		if(Dashboard.DUAL.equals(type)){
			query = DashboardQueryBuilder.findDualDashboardById();
			mapper = new DualDashboardRowMapper();
		} else {
			query = DashboardQueryBuilder.findQuadDashboardById();
			mapper = new QuadDashboardRowMapper();
		}
		
		return (Dashboard)jdbcTemplate.queryForObject(query, params, mapper);
	}

}
